﻿using AgencyManagerSystem.Core;
using AgencyManagerSystem.Common;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Newtonsoft.Json.Serialization;
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace AgencyManagerSystem
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            try { InitHelper.InitVariable(Configuration); } catch (Exception ex) { Variable.ERROR = ex.StackTrace; }
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options => options.AddPolicy("any", builder => builder.AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials()));
            services.AddSession();
            services.AddMvc(options=> {
                options.ValueProviderFactories.Add(new JQueryQueryStringValueProviderFactory());
                options.Filters.Add(typeof(GlobalExceptions));
            }).AddJsonOptions(options => {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddAuthentication(option =>{
                option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(option => {
                option.TokenValidationParameters = Common.TokenManager.GetValidationParameters();
            });
            JwtTokenValidata jwtTokenValidata = new JwtTokenValidata();
            services.AddAuthorization(jwtTokenValidata.BindRightTable);
            services.AddSingleton<IAuthorizationHandler, RightTableAuthorizationHandler>();
            services.AddMyHttpContextAccessor();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); }
            app.UseAuthentication();
            app.UseStaticHttpContext();
            app.UseHttpsRedirection();
            app.UseMvc();
            app.UseStaticFiles();
            
        }
    }
}
